package com.liang.controller;

import com.liang.common.lang.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @name: uploadFile
 * @author: 李昂
 * @date: 2020-12-05 19:22
 * @description：uploadFile
 * @update: 2020-12-05 19:22
 */
@RestController
@RequestMapping("/upload")
public class uploadFile {


    /**
     * @Author 李昂
     * @Description 文件上传功能
     * @Date 2020/12/5 19:27
     */
    @PostMapping("/{id}")
    public Result upload(@PathVariable("id") String id, MultipartFile file, @RequestParam(value = "sno", required = false) String sno) throws IOException {
        String path = "/opt/UploadFile/";
        String filename = file.getOriginalFilename();

        String savepath = null;
        if (id.equals("0")) {
            path += "file/" + filename;
            savepath = "/api/static/file/" + filename;
        } else if (id.equals("1")) {
            filename = sno + filename.substring(filename.lastIndexOf("."));
            path += "avator/" + filename;
            savepath = "/api/static/avator/" + filename;
        } else if (id.equals("2")) {
            path += "active/" + filename;
            savepath = "/api/static/active/" + filename;
        }
        file.transferTo(new File(path));
        return Result.succ(savepath);
    }


    //删除文件
    @DeleteMapping("/{type}")
    public Result deleteFile(@PathVariable("type") String type, @RequestParam(value = "filename") String filename) {
        String path = "/opt/UploadFile/";
        if (type.equals("0")) {
            path += "file/" + filename;
        } else if (type.equals("1")) {
            path += "avator/" + filename;
        } else if (type.equals("2")) {
            path += "active/" + filename;
        }

        File file = new File(path);
        try {
            file.delete();
        } catch (Exception e) {
            return Result.fail();
        }
        return Result.succ();
    }


}
